package com.example.workbench.common.utils;

import com.example.workbench.common.vo.KaptchaCodeVo;
import com.google.code.kaptcha.Constants;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Properties;

public class CodeUtils {

    public static KaptchaCodeVo createCode() throws IOException {

        // 创建 Kaptcha 验证码生成器
        Properties properties = new Properties();
        properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, "200");
        properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, "50");
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
        Config config = new Config(properties);

        // 使用Config类初始化Producer对象
        Producer producer = config.getProducerImpl();

        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        // 生成验证码图片
        String text = defaultKaptcha.createText();
        BufferedImage bufferedImage = defaultKaptcha.createImage(text);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        // 将图片输出为字节数组流
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        // 获取验证码文本

        return new KaptchaCodeVo(text, base64Image);
    }


}
